﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace GPMS.Web.Controllers
{
    using GPMS.Model;
    using GPMS.BLL;
    public class LinkController : BaseController
    {
        public ActionResult List()
        {
            ActionHelper.GetActions(gpmsDb).ForEach(a =>
                ViewData[a.ActionID.ToString()] = Url.Action(a.Action, a.Controller));

            return View(LinkHelper.GetList(gpmsDb));
        }

        public ActionResult Edit(Guid id)
        {
            ViewData["icon"] = FileHelper.GetList(FileType.Icon, gpmsDb);

            ViewData["actions"] = ActionHelper.GetActions(gpmsDb);
            return View(LinkHelper.Get(id, gpmsDb));
        }

        [HttpPost]
        public ActionResult Edit(Guid id, FormCollection collection)
        {
            try
            {
                Link link = LinkHelper.Get(id, gpmsDb);
                UpdateModel(link, collection);
                gpmsDb.SaveChanges();
                return Success(null);
            }
            catch (Exception ex)
            {
                return JsonError("更新失败:" + ex.Message);
            }

        }

        public ActionResult Create(string type)
        {
            ViewData["icon"] = FileHelper.GetList(FileType.Icon, gpmsDb);

            ViewData["actions"] = ActionHelper.GetActions(gpmsDb);
            return View(new Link());
        }

        [HttpPost]
        public ActionResult Create(string type,Link link)
        {
            if (ModelState.IsValid)
            {
                LinkHelper.Add(type,link, gpmsDb);
                return Success(null);
            }
            return JsonError(GetError(ModelState));
        }

        public ActionResult Delete(Guid id)
        {
            return Confirm(
                string.Format("您确定删除连接:{0} 吗?", LinkHelper.Get(id, gpmsDb).LinkName)
                );
        }

        [HttpPost]
        public ActionResult Delete(Guid id, FormCollection collection)
        {
            try
            {
                LinkHelper.Delete(id, gpmsDb);
                return Success(null);
            }
            catch (Exception ex)
            {
                return JsonError("更新失败:" + ex.Message);
            }
        }

    }
}
